package edu.hawaii.halealohacli.kmj;

import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.sensordata.jaxb.SensorData;

/**
 * Retrieves the current-power usage of locations within the Hale Aloha dormitories.
 * @author Jesse Elfalan
 *
 */
public class CurrentPower implements Command {
 

     private long Pow = 0;
     private String Name;
     private String TimeStamp;
     
     /**
      * Constructor for CurrentPower.
      * @param client client to be used
      * @param towerLounge Location to be used
      */
     public CurrentPower(WattDepotClient client,String towerLounge) {
        
       Name = towerLounge;
      
      //get power of desired source
      try {
        SensorData sensorData = null;
        double power = 0;
        sensorData = client.getLatestSensorData(Name);
        power = client.getLatestPowerConsumed(Name);
        power = power / 1000;
        Pow = (long)power;
        
        TimeStamp = ((sensorData.getTimestamp()).normalize()).toString();
        if (power == 0) {
          //if(powerData == null){
          System.err.println("Unable to retrieve power data");
        }
      }
      catch (NotAuthorizedException e) {
        System.err.println("Not authorized to view source");
      }
      catch (ResourceNotFoundException e) {
        System.err.println("Source name not found");
      }
      catch (BadXmlException e) {
        System.err.println("server provided bad xml:" + e.toString());
      }
      catch (MiscClientException e) {
        System.err.println("problem encountered with server:" + e.toString());
      }
      catch (NullPointerException e) {
        System.err.println("there was nothing found!");
      }
  }
     @Override
     public void printResult() {
       System.out.println( Name + "'s power as of " + TimeStamp.substring(0,TimeStamp.indexOf('T'))
                                + " is " + Pow + " kW");
     }
     
     /**
      * Returns name of source being used.
      * 
      * @return Source (tower/lounge) name.
      */
     public String getName() {
       return this.Name;
     }
     
     /**
      * Returns detected power usage of source in kWh.
      * 
      * @return Source (tower/lounge) power consumption for current day in kWh.
      */
     public long getPower() {
       return this.Pow;
     }
  }
  
  